<template>
  <div class="basetable" element-loading-text="拼命加载中">
    <!-- v-loading 设置加载 -->
    <div class="selectMenu">
      <el-button size="small" type="primary" @click="add">新增角色</el-button>
      <span class="spansearch">角色名称:</span>
      <el-input
        size="small"
        placeholder="姓名搜索"
        style="width:350px;margin-left: 16px;"
        @input="searchClick"
        clearable
        v-model="input1"
      ></el-input>

      <el-dialog width="500px" title="新增角色" :visible.sync="dialogFormVisiblea" @close='closeDialog'>
        <!-- 新增 -->
        <el-form :model="form">
          <el-form-item label="姓名" :label-width="formLabelWidth">
            <el-input v-model="form.name" auto-complete="off" @change="changea()"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <!-- 设置触发更新的方法 -->
          <el-button type="primary" @click="updatea">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <div class="tableMain">
      <el-table
        :data="userList.slice((currentPage-1)*pagesize,currentPage*pagesize)"
        stripe
        style="width: 100%"
      >
        <el-table-column type="index" width="100" label="序号"></el-table-column>
        <el-table-column prop="name" label="角色名称"></el-table-column>
        <!-- <el-table-column prop="description" label="职务"></el-table-column> -->
        <el-table-column label="操作" width="250">
          <template slot-scope="scope">
            <!-- 点击编辑进入编辑页面进行编辑表格数据 -->
            <el-button size="medium" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button size="medium" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 下面这个用来设置点击添加按钮的弹出框，里面可以进行嵌套表格来展示弹出的表格信息,使用下面的:visible.sync来控制显示与否 -->
    <!-- 里面绑定的是我们新设置的值，填写完成后，将我们这个新值塞到页面中所有的数据当中去 -->
    <el-dialog title="权限分配" :visible.sync="dialogFormVisible">
      <!-- 在el-dialog中进行嵌套el-form实现弹出表格的效果 -->
      <el-form :model="form">
        <el-form-item label="姓名" :label-width="formLabelWidth">
          <el-input v-model="form.name" auto-complete="off" @change="changea()"></el-input>
        </el-form-item>

        <el-form-item label="权限分配" :label-width="formLabelWidth">
          <el-tree
            ref="tree"
            @check-change="changetree"
            :data="data"
            show-checkbox
            node-key="id"
            :default-checked-keys="adminurl"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <!-- 设置触发更新的方法 -->
        <!-- <el-button type="primary" @click="update">确 定</el-button> -->
        <el-button type="primary" @click="updataedit()">确 定</el-button>
      </div>
    </el-dialog>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 25, 50,100]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="userList.length"
    ></el-pagination>
  </div>
</template>

<script>
import axios from "axios"
import baseUrl from "../../config/index"
export default {
  data() {
    return {
      currentPage:1, //初始页
      pagesize:10,    //    每页的数据
      userList: [],
      data: [],
      defaultProps: {
        label: "name",
        id: "id",
      },
      adminid:"",

      dialogFormVisible: false,
      dialogFormVisiblea: false,
      formLabelWidth: "80px",
      // 设置form用于进行添加的时候绑定值
      form: {
        name: "",
        id: "",
      },
      value6: "",
      currentPage3: 1,
      currentIndex: "",

      RoleLists: [],
      roleID: [],
      input: "",
      roledalete: [],
      roleedit: {},
      quanxianid: [],
      input1: "", //搜索
      urlstr:"",
      qxurl:"",
      adminurl:[],
    };
  },

  created() {
    this.roleLists();
    this.mensLists();
  },

  methods: {       
    closeDialog(){
      if ( this .$refs["form"]!==undefined) {
          this.$refs["form"].resetFields();
      }
    },
    changetree(){
      let stringurl = this.$refs.tree.getCheckedKeys()
      // console.log("stringurl",stringurl);
      this.urlstr = stringurl.join(",")
      // console.log("this.urlstr",this.urlstr);
    },
    // 初始页currentPage、初始每页数据数pagesize和数据data
        handleSizeChange: function (size) {
                this.pagesize = size;
        },
        handleCurrentChange: function(currentPage){
                this.currentPage = currentPage;
        },
    //角色创建
    async update() {
      //   将我们添加的信息提交到总数据里面
      // this.tableData.push(this.form);

      this.RoleLists = (
        await this.$api.home.roleAdd({
          name: this.form.name,
        })
      ).data;
      this.dialogFormVisible = false;
      this.dialogFormVisiblea = false;
    },
    //权限分配树
    async mensLists() {
      this.data = (await this.$api.home.mensLists()).data.data;
    },
    changea() {
    },
    //角色列表
    async roleLists() {
      this.userList = (await this.$api.home.roleLists({})).data.data;
      let a = "";
      this.userList.forEach(function (e) {
        a += e.id + ",";
      });
      a = a.substring(0, a.length - 1);
      this.roleID = a.split(",");
    },

    // 增加数据的方式，单独的设置一些值，用于增加功能，这些值放在对象里面进行设置，然后将这个新增的对象塞到总数据里面
    add() {
      this.form = {
        name: "",
      };
      //   设置点击按钮之后进行显示对话框
      this.dialogFormVisiblea = true;
    },
    

    async updatea() {
      this.RoleLists = (
        await this.$api.home.roleAdd({
          name: this.form.name,
        })
      ).data;

      if (this.RoleLists.code == 401) {
        this.$notify.error({
          title: "错误",
          message: this.RoleLists.msg,
        });
      } else if (this.RoleLists.code == 200) {
        this.$notify({
          title: "成功",
          message: this.RoleLists.msg,
          type: "success",
        });
         this.roleLists();
      }
      this.dialogFormVisiblea = false;
    },

    //编辑角色分配权限

    async updataedit() {
    
      this.adminurl = []
      let a = this.quanxianid;
      let b = a.join(",");
      this.roleedit = (
        await this.$api.home.roleAccess({
          id: this.form.id,
          url: this.urlstr,
        })  
      ).data;

      if(this.roleedit.code == 200){
         this.$message({
          message: this.roleedit.msg,
          type: 'success'
        });
      }else{
         this.$message.error(this.roleedit.msg);
      }      
      this.dialogFormVisible = false;
      this.dialogFormVisiblea = false;
    },
    getCheckedKeys() {
      this.quanxianid = this.$refs.tree.getCheckedKeys();
    },

    //删除角色

     handleDelete(index, row) {
       let Url = baseUrl.DevUrl
       let id =row.id
       let token = localStorage.getItem('token').replace("\"", "");
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
      }).then(() => {
        axios({
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'token':token
            },
            method: 'post',
            type:'JSON',
            url: Url + '.role/delete',
            params: {
              id:id
            }
        }).then(res=>{
            if (res.data.code == 200) {
            this.$message({
                message: res.data.msg,
                type: 'success'
              });
              this.roleLists();
          }else{
            this.$message.error(res.data.msg);
          }
        })
      }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
     
    },

    async handleEdit(index, row) {
      this.adminid = row.id
      console.log("row.id");
      // 将数据的index传递过来用于实现数据的回显
      this.form = this.userList[index];
      this.currentIndex = index;
      // 设置对话框的可见
      this.dialogFormVisible = true;
      // this.roleShow()
      let baseul = (await this.$api.home.roleShow({
        id:this.adminid
      })).data
      console.log("adminid",this.adminid);
      console.log("baseul",baseul);
      if(baseul.code == 200){
        let a = baseul.data.url
        this.adminurl = a
        this.$refs.tree.setCheckedNodes(a)
      }
      console.log("adminurl",this.adminurl);
    
    },

    cancel() {
      // 取消的时候直接设置对话框不可见即可
      this.dialogFormVisible = false;
      this.dialogFormVisiblea = false;
    },

     //搜索
    searchClick() {
      let searchText = this.input1;
      let list = [];
      if (searchText) {
        list = this.userList.filter(e => {
          return e.name.match(searchText);
        });
        this.userList = list;
      } else {
        this.roleLists();
      }
    }
  },
};
</script>

<style lang="less" scope>
.tableMain {
  margin-top: 10px;
}
//搜索框文字
.spansearch {
  color: #409eff;
  font-size: 15px;
  margin-left: 20px;
}

.page {
  float: left;
  margin-top: 10px;
}

.el-input--suffix {
  .el-input-group__append {
    border-color: #1890ff;
    .btnSearch {
      background: #1890ff;
      color: #fff;
      border-radius: 0;
    }
  }
}
</style>